﻿function searchBtnOnClickHandler() {
    var userInputMovieName = $("#searchBox").val();
    searchMovieByTitle(userInputMovieName);
}

function searchMovieByTitle(movieTitle) {
    if (movieTitle) {
        var urlWithParameters = "http://www.omdbapi.com/?t=" + encodeURI(movieTitle) + "&y=&plot=short&r=json";
        console.log("The URL to hit is: " + urlWithParameters);
        $.ajax({
            url: urlWithParameters,
            method: "GET",
            dataType: "json",
            success: function (response) {
                populateUIWithResults(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("An error occurred: " + textStatus);
            }
        });
    } else {
        alert("Please enter a movie title and try again");
    }
}

function populateUIWithResults(movieResponse) {
    if (movieResponse) {
        console.log("A response is received from the web service");
        if (movieResponse.Response) {
            $("#title").html(movieResponse.Title);
            $("#year").html(movieResponse.Year);
            $("#genre").html(movieResponse.Genre);
            $("#actors").html(movieResponse.Actors);
            $("#plot").html(movieResponse.Plot);
            $("#language").html(movieResponse.Language);
            $("#imdbRating").html(movieResponse.imdbRating);
            $("#duration").html(movieResponse.Runtime);
            $("#poster").attr("src", movieResponse.Poster);
        } else {
            alert(movieResponse.Error);
        }
    } else {
        console.log("No response is received from the web service");
        alert("No response is received from the web service")
    }
}